package com.example.quizamination.ui.main

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.example.quizamination.R
import com.example.quizamination.adapters.QuestionsAdapter
import com.example.quizamination.databinding.FragmentMainBinding
import com.example.quizamination.quiz.Quiz
import com.example.quizamination.quiz.QuizStorage

class MainFragment : Fragment() {
    private var _binding: FragmentMainBinding? = null
    private val binding: FragmentMainBinding
        get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    private val quiz: Quiz = QuizStorage.getQuiz(QuizStorage.Locale.Ru)
    private var answers: MutableList<Int> = MutableList<Int>(quiz.questions.size) { -1 }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        val questionsAdapter: QuestionsAdapter =
            QuestionsAdapter(requireContext(), quiz.questions, answers)
        binding.questionsListView.adapter = questionsAdapter
        binding.resultButton.setOnClickListener {
            if (!(-1 in answers)) {
                val res = QuizStorage.answer(quiz, answers)
                val bundle: Bundle = Bundle().apply {
                    putString("resultText", res)
                }
                findNavController().navigate(R.id.action_mainFragment_to_resultFragment, bundle)
            } else {
                Toast.makeText(activity, "Please answer all questions!", Toast.LENGTH_LONG).show()
            }
        }
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}